<?php
declare (strict_types = 1);
/**
 * 管理员
 */
namespace app\common\admin;

use app\common\facade\model\PgmInfoModel; // 引入节目库模型
use app\common\facade\model\PgmInfoPlayModel; //  引入节目播放信息模型
use app\common\facade\model\AdvPgmInfoModel;  // 引入广告库模型
use app\common\facade\model\ChannelInfoModel;
use app\common\facade\model\AdvPgmListModel;
use app\common\facade\model\AdvPgmListDetailModel;
use app\common\facade\model\MaterialModel; // 引入素材类模型门面代理
use app\common\facade\model\AdvseqModel;

class AdvPgmList extends BaseAdmin
{

    public function advpgmgroupList($param) 
    {
        if (!isset($param['type'])) exception('节目组参数异常!');

        if(isset($param['ordername']) || isset($param['order'])) {
            $ordername = $param['ordername'] ?: 'play_order';
            $order = $param['order'] == 'descending' ? 'desc' : 'asc';
        }

        $where = [];
        $where[] = ['pl_id', '=', $param['type']];
        // 判断节目单时段ID
        if (!empty($param['advseq'])) {
            if ($param['advseq'] != 'all') {
                $where[] = ['advseg_id', '=', $param['advseq']];
            }
        } 

        return AdvPgmListDetailModel::detailLists($where, $ordername, $order);
    }

    public function advpgmgroupAdd($param)
    {
        // 判断节目单日期单是否存在
        if (!empty($param['pl_id'])) {
            // 查询日期广告节目单详情
            $pl_info = AdvPgmListModel::info(['pl_id'=>intval($param['pl_id'])]);
            // 查询用户信息
            $adminLoginInfo = $this->adminLoginInfo();
            if ($pl_info['check_flag'] == 1) {
                return ['code'=>400, 'msg'=>'该节目单已审核，无法添加和移动！'];
            }
            // 查询节目单是否已过期（播出日志是否小于当前日期）
            if ($pl_info['play_date'] < date('Y-m-d')) {
                return ['code'=>400, 'msg'=>'该节目单已过期，无法添加和移动！'];
            }
            if ($param['add_type'] == 'add') {
                // 新增分为素材新增和广告库新增，此处判断
                if (!empty($param['pgm'])) {
                    // 广告库新增逻辑
                    if (!empty($param['mat_id'])) {
                        $matArr = explode(',', $param['mat_id']);
                        $word = '';
                        foreach($matArr as $k => $v) {
                            $data = [];
                            
                            // 添加新的广告库素材到节目单中，先检查此广告库素材是否为空
                            if (!empty($v)) {
                                // 广告节目单日期单主键ID
                                $data['pl_id']      = intval($param['pl_id']);

                                // 在选择节目时段为全部时，默认advseq为当前节目时段最靠前的时段
                                if ($param['advseq'] == 'all') {
                                    // 找到所有满足条件的节目时段
                                    $advseqList = $this->getadvseqList(['channel_id'=>$pl_info['channel_id'],'play_date'=>$pl_info['play_date']]);
                                    // 节目单时段主键ID
                                    $data['advseg_id']  = $advseqList['list'][0]['adv_seq_id'];
                                }else{
                                    // 节目单时段主键ID
                                    $data['advseg_id']  = intval($param['advseq']);
                                }
                                
                                // 节目单排序，先查看当前表中最大的排序值，自动加一
                                $max_sort = AdvPgmListDetailModel::max_sort(['pl_id'=>intval($param['pl_id']),'advseg_id'=>$data['advseg_id']]);
                                $data['play_order'] = $max_sort+1;

                                // 素材详情填入相关字段
                                $pgm_info = AdvPgmInfoModel::info(['pgm_id'=>$v]);
                                $data['pgm_name'] = $pgm_info['pgm_name'];
                                $data['pgm_type'] = $pgm_info['pgm_type'];
                                $data['markin']   = $pgm_info['markin'];
                                $data['markout']  = $pgm_info['markout'];
                                $data['pgm_len']  = $pgm_info['markout'] - $pgm_info['markin'] + 1;
                                $data['pgm_id']   = $pgm_info['pgm_id'];
                                // 素材主键ID
                                $data['mat_id']   = $pgm_info['mat_id'];

                                $data['create_time'] = time();

                                $m = AdvPgmListDetailModel::addEditSave($data);
                                // 添加成功后增加成功日志
                                if ($m) {
                                    // 执行增加广告节目单广告库日志
                                    $ch_info  = ChannelInfoModel::info(['id'=>$pl_info['channel_id']]);
                                    $adv_info = AdvseqModel::info(['adv_seq_id'=>$data['advseg_id']]);
                                    $word .= '用户['.$adminLoginInfo['username'].'] 从广告库将广告节目['.$data['pgm_name'].'](节目ID:'.$data['pgm_id'].')(素材ID:'.$data['mat_id'].')加入到广告节目单 ['.$ch_info['channel_name'].']-['.$pl_info['play_date'].']，时段['.$adv_info['adv_seg_name'].']的位置['.$data['play_order'].']！';
                                    
                                }
                            }
                        }
                        self::syslog('pro', $word, $adminLoginInfo);
                    }
                }else{
                    // 素材新增逻辑
                    if (!empty($param['mat_id'])) {
                        $matArr = explode(',', $param['mat_id']);
                        $word = '';
                        foreach($matArr as $k => $v) {
                            $data = [];
                            // 添加新的素材到节目单中，先检查此素材是否为空
                            if (!empty($v)) {
                                // 素材主键ID
                                $data['mat_id']     = intval($v);
                                // 广告节目单日期单主键ID
                                $data['pl_id']      = intval($param['pl_id']);

                                // 在选择节目时段为全部时，默认advseq为当前节目时段最靠前的时段
                                if ($param['advseq'] == 'all') {
                                    // 找到所有满足条件的节目时段
                                    $advseqList = $this->getadvseqList(['channel_id'=>$pl_info['channel_id'],'play_date'=>$pl_info['play_date']]);
                                    // 节目单时段主键ID
                                    $data['advseg_id']  = $advseqList['list'][0]['adv_seq_id'];
                                }else{
                                    // 节目单时段主键ID
                                    $data['advseg_id']  = intval($param['advseq']);
                                }
                                
                                // 节目单排序，先查看当前表中最大的排序值，自动加一
                                $max_sort = AdvPgmListDetailModel::max_sort(['pl_id'=>intval($param['pl_id']),'advseg_id'=>$data['advseg_id']]);
                                $data['play_order'] = $max_sort+1;

                                // 素材详情填入相关字段
                                $mat_info = MaterialModel::info(['mat_id'=>$v]);
                                $data['pgm_name'] = $mat_info['mat_name'];
                                $data['pgm_type'] = $mat_info['mat_type'];
                                $data['markin']   = $mat_info['markin'];
                                $data['markout']  = $mat_info['markout'];
                                $data['pgm_len']  = $mat_info['markout'] - $mat_info['markin'] + 1;

                                $data['create_time'] = time();

                                $m = AdvPgmListDetailModel::addEditSave($data);
                                // 添加成功后增加成功日志
                                if ($m) {
                                    // 执行增加广告节目单素材库日志
                                    $ch_info  = ChannelInfoModel::info(['id'=>$pl_info['channel_id']]);
                                    $adv_info = AdvseqModel::info(['adv_seq_id'=>$data['advseg_id']]);
                                    $word .= '用户['.$adminLoginInfo['username'].'] 从素材库将广告节目['.$data['pgm_name'].'](素材ID:'.$data['mat_id'].')加入到广告节目单 ['.$ch_info['channel_name'].']-['.$pl_info['play_date'].']，时段['.$adv_info['adv_seg_name'].']的位置['.$data['play_order'].']！';
                                    
                                }
                            }
                        }
                        self::syslog('pro', $word, $adminLoginInfo);
                    }
                }
                return $m;

            }elseif ($param['add_type'] == 'changesort') {
                $old_id = !empty($param['old_id']) ? $param['old_id'] : null;
                $new_id = !empty($param['new_id']) ? $param['new_id'] : null;
                $oldArr = explode(',', $param['old_id']);
                $newArr = explode(',', $param['new_id']);
                $where  = [];
                $params = [];
                // 素材调整排序逻辑
                // 素材调整排序时传过来的old_id其实是要移动的那个素材内容的主键ID：id
                // 素材调整排序时传过来的new_id其实是被old_id往下挤一位的那个素材内容的主键ID：id
                // 替换分为从下往上移动替换（$oldArr[1] > $newArr[1]）和从上往下移动替换（$oldArr[1] < $newArr[1]）两种方式
                if (!empty($oldArr[0]) && !empty($newArr[0]) ) {  
                    // 查询要移动的素材的详情
                    $old_info = AdvPgmListDetailModel::info(['id'=>intval($oldArr[0])]);
                    // 查询被移动的素材的详情
                    $new_info = AdvPgmListDetailModel::info(['id'=>intval($newArr[0])]);
                    // 从下往上移动替换
                    if ($oldArr[1] > $newArr[1]) {
                        // 1、变更要移动素材的时段ID和排序
                        $where['id']          = intval($old_info['id']);
                        $params['advseg_id']  = $new_info['advseg_id'];
                        $params['play_order'] = $new_info['play_order'];
                        $m = AdvPgmListDetailModel::dateUpdate($params, $where);

                        // 移动成功后增加日志
                        if ($m) {
                            // 执行移动广告节目单素材日志
                            $ch_info  = ChannelInfoModel::info(['id'=>$pl_info['channel_id']]);
                            $nadv_info = AdvseqModel::info(['adv_seq_id'=>$new_info['advseg_id']]);
                            $oadv_info = AdvseqModel::info(['adv_seq_id'=>$old_info['advseg_id']]);
                            $word = '用户['.$adminLoginInfo['username'].'] 移动节目素材 ['.$new_info['pgm_name'].'](节目ID:'.$new_info['pgm_id'].')(素材ID:'.$new_info['mat_id'].') 在广告节目单 ['.$ch_info['channel_name'].']-['.$pl_info['play_date'].']中，从 时段['.$oadv_info['adv_seg_name'].']的位置['.$old_info['play_order'].'] 到 时段['.$nadv_info['adv_seg_name'].']的位置['.$params['play_order'].']！';
                            $this->syslog('pro', $word, $adminLoginInfo);
                        }

                        // 2、查询被移动素材排序值的下面所有素材，跟被移动素材一起调整排序
                        $where   = [];
                        $where[] = ['pl_id', '=', $new_info['pl_id']];
                        $where[] = ['advseg_id', '=', $new_info['advseg_id']];
                        $where[] = ['play_order', '>', $new_info['play_order']];
                        $list    = AdvPgmListDetailModel::listsAll($where,[],'play_order ASC')->toArray();
                        // 将被移动素材加入数组中，放在第一位
                        $list = array_merge(['0'=>$new_info],$list);
                        
                        if (!empty($list)) {
                            // 遍历修改排序值
                            foreach ($list as $k => $val) {
                                $where                = [];
                                $params               = [];
                                $where['id']          = intval($val['id']);
                                $params['play_order'] = $new_info['play_order'] + $k + 1;
                                $m                    = AdvPgmListDetailModel::dateUpdate($params, $where);
                            }
                        }
                    }// 从上往下移动替换
                    elseif ($oldArr[1] < $newArr[1]) {
                        // 从上往下替要移动的素材要排序要在被移动素材的下方
                        // 1、查询被移动素材排序值的下面所有素材，调整排序
                        $where   = [];
                        $where[] = ['pl_id', '=', $new_info['pl_id']];
                        $where[] = ['advseg_id', '=', $new_info['advseg_id']];
                        $where[] = ['play_order', '>', $new_info['play_order']];
                        $list    = AdvPgmListDetailModel::listsAll($where,[],'play_order ASC')->toArray();
                        
                        if (!empty($list)) {
                            // 遍历修改排序值
                            foreach ($list as $k => $val) {
                                $where                = [];
                                $params               = [];
                                $where['id']          = intval($val['id']);
                                // 此处主要，+2是因为需要把$new_info['play_order']+1留给从上移动的素材
                                $params['play_order'] = $new_info['play_order'] + $k + 2;
                                $m                    = AdvPgmListDetailModel::dateUpdate($params, $where);
                            }
                        }
                        // 2、修改要移动素材的时段ID和排序
                        $where   = [];
                        $where['id']          = intval($oldArr[0]);
                        $params['advseg_id']  = $new_info['advseg_id'];
                        $params['play_order'] = $new_info['play_order'] +1;
                        $m = AdvPgmListDetailModel::dateUpdate($params, $where);

                        // 移动成功后增加日志
                        if ($m) {
                            // 执行移动广告节目单素材日志
                            $ch_info  = ChannelInfoModel::info(['id'=>$pl_info['channel_id']]);
                            $nadv_info = AdvseqModel::info(['adv_seq_id'=>$new_info['advseg_id']]);
                            $oadv_info = AdvseqModel::info(['adv_seq_id'=>$old_info['advseg_id']]);
                            $word = '用户['.$adminLoginInfo['username'].'] 移动节目素材 ['.$new_info['pgm_name'].'](节目ID:'.$new_info['pgm_id'].')(素材ID:'.$new_info['mat_id'].') 在广告节目单 ['.$ch_info['channel_name'].']-['.$pl_info['play_date'].']中，从 时段['.$oadv_info['adv_seg_name'].']的位置['.$old_info['play_order'].'] 到 时段['.$nadv_info['adv_seg_name'].']的位置['.$params['play_order'].']！';
                            $this->syslog('pro', $word, $adminLoginInfo);
                        }
                    }

                    // 3、为保持统一，刷新移动的那个素材所在广告节目单所有素材的排序
                    $m = $this->sortadvseq(['advseg_id'=>$old_info['advseg_id'],'pl_id'=>$old_info['pl_id']]);

                }else{
                    $m = false;
                }

                return $m;
            }else{
                return false;
            }
        }else{
            return false;
        }
        
    }

    // 新增方法：重新保存所有节目日期单的素材
    public function advpgmgroupNewAdd($param)
    {
        if(!empty($param['pl_id'])) {
            // 删除所有已存在日期单记录
            $ids_arr = array_column($param['pl_id'], 'id');
            if (!empty($ids_arr)) {
                $ids = implode(',', $ids_arr);
                $m = $this->advpgmgroupDel($ids, 'nolog');
            }
            // 查询当前广告单详情
            $pl_info = AdvPgmListModel::info(['pl_id'=>intval($param['pl_id'][0]['pl_id'])]);
            // 找到所有满足条件的节目时段
            $advseqList = $this->getadvseqList(['channel_id'=>$pl_info['channel_id'],'play_date'=>$pl_info['play_date']]);
            // 重新添加当前记录
            $add_arr = [];
            foreach ($param['pl_id'] as $k => $val) {
                $add_arr[$k]['pl_id']       = $val['pl_id'];

                // 在选择节目时段为全部时，默认advseq为当前节目时段最靠前的时段
                if ($val['advseg_id'] == 'all') {
                    // 节目单时段主键ID
                    $add_arr[$k]['advseg_id'] = $advseqList['list'][0]['adv_seq_id'];
                }else{
                    // 节目单时段主键ID
                    $add_arr[$k]['advseg_id'] = intval($val['advseg_id']);
                }
                $add_arr[$k]['pgm_id']      = $val['pgm_id'];
                $add_arr[$k]['pgm_name']    = $val['pgm_name'];
                $add_arr[$k]['play_order']  = $val['play_order'];
                $add_arr[$k]['pgm_len']     = $val['pgm_len'];
                $add_arr[$k]['pgm_type']    = $val['pgm_type'];
                $add_arr[$k]['mat_id']      = $val['mat_id'];
                $add_arr[$k]['markin']      = $val['markin'];
                $add_arr[$k]['markout']     = $val['markout'];
                $add_arr[$k]['ext_only_id'] = $val['ext_only_id'];
                $add_arr[$k]['create_time'] = empty($val['create_time']) ? date('Y-m-d H:i:s'): $val['create_time'];
                $add_arr[$k]['up_time']     = date('Y-m-d H:i:s');
            }
            $ss = AdvPgmListDetailModel::insertAll($add_arr);
            
            // 找到所有该节目单下面的已存在的节目时段，然后排序
            $advseg_arr = AdvPgmListDetailModel::groupadvseg(['pl_id'=>$pl_info['pl_id']]);
            foreach ($advseg_arr as $k => $val) {
                $this->sortadvseq(['advseg_id'=>$val['advseg_id'],'pl_id'=>$pl_info['pl_id']]);
            }

            return [
                'code' => $ss ? 1 : 0,
                'msg'  => $ss ? '添加成功' : '添加失败'
            ];
        }else{
            return [
                'code' => 0,
                'msg'  => '参数未定义'
            ];
        }
    }

    // 删除广告节目单
    public function advpgmgroupDel($ids, $type=null)
    {
        // 当ids 不为空时
        if(!empty($ids)) {
            // 查询用户信息
            $adminLoginInfo = $this->adminLoginInfo();

            // 删除后重新排列一下当前频道日期下所有时段的排序值
            // 重排列节目单内所有时段内的排序值
            $id_array = explode(',', $ids);
            $pl_info = AdvPgmListDetailModel::info(['id'=>$id_array[0]]);

            $word = '';
            if ($type != 'nolog') {
                // 增加删除日志
                foreach ($id_array as $val) {
                    
                    $ad_info = AdvPgmListDetailModel::info(['id'=>$val]);
                    $p_info  = AdvPgmListModel::info(['pl_id'=>$ad_info['pl_id']]);
                    $ch_info = ChannelInfoModel::info(['id'=>$p_info['channel_id']]);
                    $adv_info = AdvseqModel::info(['adv_seq_id'=>$ad_info['advseg_id']]);
                    // 执行删除广告节目时段日志
                    $word .= '用户['.$adminLoginInfo['username'].'] 删除广告节目单 ['.$ch_info['channel_name'].']-['.$p_info['play_date'].']，时段['.$adv_info['adv_seg_name'].']的位置['.$ad_info['play_order'].']上的 节目素材 ['.$ad_info['pgm_name'].'](节目ID:'.$ad_info['pgm_id'].')(素材ID:'.$ad_info['mat_id'].')！';
                    
                }
                self::syslog('pro', $word, $adminLoginInfo);
            }
            
            // 完成操作后再删除记录
            $res = AdvPgmListDetailModel::deleteData([['id', 'in', $ids]]);

            // 找到所有该节目单下面的已存在的节目时段，然后排序
            $advseg_arr = AdvPgmListDetailModel::groupadvseg(['pl_id'=>$pl_info['pl_id']]);
            
            foreach ($advseg_arr as $k => $val) {
                $m[] = $this->sortadvseq(['advseg_id'=>$val['advseg_id'],'pl_id'=>$pl_info['pl_id']]);
            }

            return [
                'code' => $res ? 1 : 0,
                'msg'  => $res ? '删除成功' : '删除失败'
            ];
            
        } else {
            return [
                'code' => 0,
                'msg'  => '参数未定义'
            ];
        }
    }

    // 广告节目单日期单复制素材
    public function copyadvpgms($param)
    {
        // 复制广告节目单内容，并把该节目单的排序放在最末
        $where = [];
        if (!empty($param['id'])) $where['id'] = intval($param['id']);
        $info = [];
        $info = AdvPgmListDetailModel::info($where);
        
        // 节目单排序，先查看当前表中最大的排序值，自动加一
        $max_sort = AdvPgmListDetailModel::max_sort(['pl_id'=>intval($info['pl_id']),'advseg_id'=>$info['advseg_id']]);
        
        $data['pl_id']       = $info['pl_id'];
        $data['advseg_id']   = $info['advseg_id'];
        $data['mat_id']      = $info['mat_id'];
        $data['pgm_id']      = $info['pgm_id'];
        $data['pgm_name']    = $info['pgm_name'];
        $data['pgm_type']    = $info['pgm_type'];
        $data['markin']      = $info['markin'];
        $data['markout']     = $info['markout'];
        $data['pgm_len']     = $info['pgm_len'];
        $data['ext_only_id'] = $info['ext_only_id'];
        $data['play_order']  = $max_sort + 1;
        $data['create_time'] = date('Y-m-d H:i:s');

        $m = AdvPgmListDetailModel::addEditSave($data);
        // 添加成功后增加成功日志
        if ($m) {
            // 执行复制广告节目单素材日志
            // 查询用户信息
            $adminLoginInfo = $this->adminLoginInfo();
            $pl_info = AdvPgmListModel::info(['pl_id'=>$data['pl_id']]);
            $ch_info  = ChannelInfoModel::info(['id'=>$pl_info['channel_id']]);
            $adv_info = AdvseqModel::info(['adv_seq_id'=>$data['advseg_id']]);
            $word = '用户['.$adminLoginInfo['username'].'] 复制节目素材 ['.$data['pgm_name'].'](节目ID:'.$data['pgm_id'].')(素材ID:'.$data['mat_id'].')加入到广告节目单 ['.$ch_info['channel_name'].']-['.$pl_info['play_date'].']，时段['.$adv_info['adv_seg_name'].']的位置['.$data['play_order'].']！';
            $this->syslog('pro', $word, $adminLoginInfo);
        }
        return $m;
    }

    // 统计广告节目单日期单素材播出次数
    public function totaladvpgms($param)
    {
        // 统计素材播出次数要注意，有两种素菜类型
        // 1、广告库导入的素材，pgm_id有值，则统计所有pgm_id相等的素材
        // 2、素材库导入的素材  pgm_id为空，则统计所有pgm_id为空且mat_id相等的素材
        $where       = [];
        $count_where = [];
        if (!empty($param['id'])) $where['id'] = intval($param['id']);
        $info = AdvPgmListDetailModel::info($where);
        if (!empty($info['pgm_id'])) {
            $count_where[] = ['pgm_id', '=', $info['pgm_id']];
        }else{
            $count_where[] = ['pgm_id', '=', null];
            $count_where[] = ['mat_id', '=', $info['mat_id']];
        }
        $count_where[] = ['pl_id', '=', $info['pl_id']];
        
        // 统计素材条数
        $max_sort = AdvPgmListDetailModel::max_count($count_where);

        return $max_sort;
    }

    // 多重删除广告节目单日期单素材
    public function delmoreadvpgms($param)
    {
        // 删除所有同类型的素材要注意，有两种素材类型
        // 1、广告库导入的素材，pgm_id有值，则统计所有pgm_id相等的素材
        // 2、素材库导入的素材  pgm_id为空，则统计所有pgm_id为空且mat_id相等的素材
        $where       = [];
        $group_where = [];
        if (!empty($param['id'])) $where['id'] = intval($param['id']);
        $info = AdvPgmListDetailModel::info($where);
        if (!empty($info['pgm_id'])) {
            $group_where[] = ['pgm_id', '=', $info['pgm_id']];
        }else{
            $group_where[] = ['pgm_id', '=', null];
            $group_where[] = ['mat_id', '=', $info['mat_id']];
        }
        $group_where[] = ['pl_id', '=', $info['pl_id']];
        
        // 所有符合条件的素材
        $group_list = AdvPgmListDetailModel::listsAll($group_where)->toArray();

        $id_arr = array_column($group_list, 'id');
        $ids    = implode(',', $id_arr);
        $m = $this->advpgmgroupDel($ids);

        return $m;
    }

    // 获取广告节目单的频道所属详情
    public function channelgroup($param)
    {
        $adv_where = [];
        
        if ($param['type'] != 'all') {
            $adv_where[] = ['play_date', '>=',date('Y-m-d',time())];
        }
        $advgroup_list = AdvPgmListModel::listsAll($adv_where,[],'play_date ASC')->toArray();
        $channel_list = ChannelInfoModel::listsAll()->toArray();
        
        $data = [];
        if($channel_list) {
            foreach($channel_list as $k => $v) {
                $data[$k]['value'] = $v['id'];
                $data[$k]['label'] = $v['channel_name'];
            }

            foreach($advgroup_list as &$c) {
                foreach($data as $d =>$f) {
                    if($c['channel_id'] == $f['value']) {
                        $data[$d]['children'][] = ['value' => $c['pl_id'], 'label' => $c['play_date'], 'status' => empty($c['check_flag']) ? 0 : $c['check_flag']];
                    }
                }
            }
        }
        return $data;
    }

    // 添加广告节目单
    public function channelgroupAddSave($param)
    {
        $s_where['play_date']  = $param['play_date'];
        $s_where['channel_id'] = $param['channel_id'];
        // 要复制的广告单日期单的pl_id
        $other_date = empty($param['other_date'])? null : $param['other_date'];
        // 要复制的广告单日期单的节目单时段
        $advseqs    = empty($param['advseqs'])? null : $param['advseqs'];
        
        $s_info  = AdvPgmListModel::info($s_where);
        // 不能创建之前日期的节目单
        if ($param['play_date'] < date('Y-m-d',time())) {
            return [
                'code' => 0,
                'msg'  => '不能创建今天之前的广告单'
            ];
        }
        // 查看节目单是否已存在
        if (empty($s_info)) {
            $where = [];
            $adminLoginInfo = $this->adminLoginInfo();
            $param['creator'] = $adminLoginInfo['id'];

            $param['create_time'] = time();
            unset($param['other_date']);
            unset($param['advseqs']);
            $m = AdvPgmListModel::adddatas($param, $where);

            if ($m) {
                // 执行增加广告节目单日志
                $ch_info = ChannelInfoModel::info(['id'=>$param['channel_id']]);
                self::syslog('pro','用户['.$adminLoginInfo['username'].'] 新增广告节目单 ['.$ch_info['channel_name'].']-['.$param['play_date'].']！',$adminLoginInfo);

                // 复制的节目单详情
                if (!empty($other_date) && !empty($advseqs)) {
                    $ss = $this->copyadvlist($other_date, $advseqs, $m);
                    if (!$ss) {
                        return ['code'=>400, 'msg'=>'复制节目单添加时出错，请检查！'];
                    }
                    $other_info = AdvPgmListModel::info(['pl_id'=>$other_date]);
                    self::syslog('pro','用户['.$adminLoginInfo['username'].'] 复制广告节目单 ['.$ch_info['channel_name'].']-['.$other_info['play_date'].'] 到 ['.$ch_info['channel_name'].']-['.$param['play_date'].']！',$adminLoginInfo);
                }
            }
            return ['code'=>200, 'data'=>$m];
        } else {
            return ['code'=>400, 'msg'=>'节目单已存在，请检查！'];
        }
    }

    // 添加广告节目单
    public function channelgroupAddEditSave($param)
    {
        $s_where['play_date']  = $param['play_date'];
        $s_where['channel_id'] = $param['channel_id'];
        $s_info = AdvPgmListModel::info($where);
        if (empty($s_info)) {
            $where = [];
            $adminLoginInfo = $this->adminLoginInfo();
            $param['creator'] = $adminLoginInfo['id'];
            if(isset($param['pl_id'])) {
                // 编辑
                $where[] = ['pl_id', '=', $param['pl_id']];
                unset($param['pl_id']);
                $param['up_time'] = time();
            }else{
                $param['create_time'] = time();
            }

            return AdvPgmListModel::addEditSave($param, $where);
        } else {
            return ['code'=>400, 'msg'=>'节目单已存在，请检查！'];
        }
    }

    // 删除广告节目单
    public function channelgroupDel($ids)
    {
        // 当ids 不为空时
        if(!empty($ids)) {
            // 增加删除日志
            $adminLoginInfo = $this->adminLoginInfo();
            $id_arr = explode(',', $ids);
            foreach ($id_arr as $k => $val) {
                $info = AdvPgmListModel::info(['pl_id'=>$val]);
                if ($info['play_date'] < date('Y-m-d',time())) {
                    return [
                        'code' => 0,
                        'msg'  => '不能删除之前日期的广告单'
                    ];
                }
                $ch_info = ChannelInfoModel::info(['id'=>$info['channel_id']]);
                // 执行删除广告节目时段日志
                $this->syslog('pro','用户['.$adminLoginInfo['username'].'] 删除广告节目单 ['.$ch_info['channel_name'].']-['.$info['play_date'].']！',$adminLoginInfo);
            }

            $res = AdvPgmListModel::deleteData([['pl_id', 'in', $ids]]);
        } else {
            return [
                'code' => 0,
                'msg'  => '参数未定义'
            ];
        }

        return [
            'code' => $res ? 1 : 0,
            'msg'  => $res ? '删除成功' : '删除失败'
        ];
    }

    // 获取特定频道的广告节目时段
    // 查询节目有效期和当天是否有效
    public function getadvseqList($param)
    {
        $where = [];

        if (isset($param['channel_id']) && !empty($param['channel_id'])) $where['channel_id'] = $param['channel_id'];
        if (isset($param['play_date']) && !empty($param['play_date'])) $where['play_date'] = $param['play_date'];

        $advseqList = AdvseqModel::advseqalive($where);

        return $advseqList;
    }

    // 获取该频道，该日期，该时段内的节目
    public function getadvseqDetail($param)
    {
        $where = [];

        if (isset($param['channel_id']) && !empty($param['channel_id'])) $newwhere['channel_id'] = $param['channel_id'];
        if (isset($param['play_date']) && !empty($param['play_date'])) $newwhere['play_date'] = $param['play_date'];

        if (!empty($newwhere)) {
            $pl_info = AdvPgmListModel::info($newwhere);
        }

        if (isset($param['advseg_id']) && !empty($param['advseg_id'])) $where['advseg_id'] = $param['advseg_id'];
        if (isset($pl_info['pl_id']) && !empty($pl_info['pl_id'])) $where['pl_id'] = $pl_info['pl_id'];

        return AdvPgmListDetailModel::getadvseqLists($where);
    }

    // 审核广告日期单
    public function reviewadvseq($param)
    {
        $where = [];

        if (isset($param['pl_id']) && !empty($param['pl_id'])) $where['pl_id'] = $param['pl_id'];
        if (isset($param['word']) && !empty($param['word'])) $update['check_mind'] = $param['word'];
        // 记录审核日志
        $adminLoginInfo = $this->adminLoginInfo();
        $info    = AdvPgmListModel::info(['pl_id'=>$param['pl_id']]);
        $ch_info = ChannelInfoModel::info(['id'=>$info['channel_id']]);

        if ($param['status'] == 1){
            $update['check_flag'] = 1;
            $word = '用户['.$adminLoginInfo['username'].'] 审核通过广告节目单 ['.$ch_info['channel_name'].']-['.$info['play_date'].']！审核意见：'.$param['word'];
        }elseif ($param['status'] == 2) {
            $update['check_flag'] = 0;
            $word = '用户['.$adminLoginInfo['username'].'] 反审广告节目单 ['.$ch_info['channel_name'].']-['.$info['play_date'].']！审核意见：'.$param['word'];
        }

        $update['check_time'] = date('Y-m-d H:i:s',time());

        $update['check_man']  = $adminLoginInfo['id'];

        // 记录审核日志
        self::syslog('pro', $word, $adminLoginInfo);

        return AdvPgmListModel::dateUpdate($update,$where);
    }

    // 节目单日期单内时段素材排序
    public function sortadvseq($param)
    {
        $where   = [];
        $list    = [];
        if(!empty($param['advseg_id'])) $where[] = ['advseg_id', '=', $param['advseg_id']];
        if(!empty($param['pl_id'])) $where[] = ['pl_id', '=', $param['pl_id']];

        $list    = AdvPgmListDetailModel::listsAll($where,[],'play_order ASC')->toArray();
        // 遍历修改排序值
        if (!empty($list)) {
            foreach ($list as $k => $val) {
                $where                = [];
                $params               = [];
                $where['id']          = intval($val['id']);
                $params['play_order'] = $k + 1;
                $m = AdvPgmListDetailModel::dateUpdate($params, $where);
            }
        }

        return $m;
    }

    // 获取频道的广告单列表
    public function getotheradvlist($param)
    {
        $where = [];

        if (isset($param['channel_id']) && !empty($param['channel_id'])) $where['channel_id'] = $param['channel_id'];

        $advList = AdvPgmListModel::listsAll($where,[],'play_date DESC')->toArray();

        return ['list'=> $advList];
    }

    // 获取特定广告节目单的广告节目时段
    public function getotheradvseq($param)
    {
        $where = [];
        if (isset($param['pl_id']) && !empty($param['pl_id'])) $where['pl_id'] = $param['pl_id'];

        $info = AdvPgmListModel::info($where);

        $advseqList = self::getadvseqList(['channel_id'=>$info['channel_id'], 'play_date'=>$info['play_date']]);

        return $advseqList;
    }

    // 复制目标广告日期单
    // tar_pl_id       复制目标广告日期单的pl_id
    // tar_adv_seg_id  复制目标广告日期单的节目时段ID，all为全部
    // pl_id           广告日期单的pl_id
    public function copyadvlist($tar_pl_id, $tar_adv_seg_id, $pl_id)
    {
        if (!empty($tar_pl_id) AND !empty($tar_adv_seg_id)) {
            $tar_info = AdvPgmListModel::info(['pl_id'=>$tar_pl_id]);
            $where = [];
            if ($tar_adv_seg_id == 'all') {
                $where[] = ['pl_id', '=', $tar_pl_id];
            }else{
                $where[] = ['pl_id', '=', $tar_pl_id];
                $where[] = ['advseg_id', '=', $tar_adv_seg_id];
            }

            $advList = AdvPgmListDetailModel::listsAll($where, [], 'create_time DESC')->toArray();
            if (!empty($pl_id)) {
                // 获取新添加日期单的可用时段
                $pl_info = AdvPgmListModel::info(['pl_id'=>$pl_id]);
                $adv_list = self::getadvseqList(['channel_id'=>$pl_info['channel_id'], 'play_date'=>$pl_info['play_date']]);
                $adv_seg_arr = array_column($adv_list['list'], 'adv_seq_id');
            }else{
                return false;
            }
            
            foreach ($advList as $k => $val) {
                // 如果复制目标广告日期单在可用时段内就添加到详情表中
                if (in_array($val['advseg_id'], $adv_seg_arr)) {
                    unset($val['id']);
                    $val['pl_id'] = $pl_id;
                    AdvPgmListDetailModel::addEditSave($val);
                }
            }
            return true;
        }else{
            return false;
        }
    }

}